// 用户注册并创建销售表
exports.registerUser = async (userData) => {
	const db = uniCloud.database();
	const {
		username,
		password
	} = userData;

	// 检查用户名是否已存在
	const existingUser = await db.collection('users').where({
		username
	}).get();
	if (existingUser.data.length > 0) {
		return {
			code: 1,
			message: '用户名已存在'
		};
	}

	try {
		// 插入新用户
		const res = await db.collection('users').add(userData);
		const userId = res.id;

		// 创建销售表 schema
		const salesTableName = `${username}-sales`;

		const salesTableSchema = {
			"bsonType": "object",
			"permission": {
				"read": true,
				"create": true,
				"update": true,
				"delete": true
			},
			"properties": {
				"_id": {
					"description": "销售记录ID，系统自动生成"
				},
				"material_name": {
					"title": "建材名称",
					"bsonType": "string",
					"description": "建材名称"
				},
				"date": {
					"title": "日期",
					"bsonType": "string",
					"description": "日期，例如: 2025-03-01"
				},
				"vehicle_number": {
					"title": "车号",
					"bsonType": "string",
					"description": "车辆编号"
				},
				"customer_name": {
					"title": "客户姓名",
					"bsonType": "string",
					"description": "客户的名称"
				},
				"customer_phone": {
					"title": "电话号码",
					"bsonType": "string",
					"description": "客户的电话号码"
				},
				"product_spec": {
					"title": "规格型号",
					"bsonType": "string",
					"description": "产品规格和型号"
				},
				"unit": {
					"title": "单位",
					"bsonType": "string",
					"description": "数量单位，例如: 件, 箱"
				},
				"quantity": {
					"title": "数量",
					"bsonType": "int",
					"minimum": 0,
					"description": "销售数量"
				},
				"unit_price": {
					"title": "售价",
					"bsonType": "double",
					"minimum": 0,
					"description": "商品的售价"
				},
				"cost_price": {
					"title": "进价",
					"bsonType": "double",
					"minimum": 0,
					"description": "单件商品进价"
				},
				"amount": {
					"title": "金额",
					"bsonType": "double",
					"description": "总金额 = 单价 × 数量"
				},
				"net_profit": {
					"title": "净利润",
					"bsonType": "double",
					"description": "净利润 = (单价 - 进价) × 数量"
				},
				"delivery_destination": {
					"title": "送货目的地",
					"bsonType": "string",
					"description": "送货目的地地址"
				},
				"status": {
					"title": "状态",
					"bsonType": "int",
					"description": "状态，0 表示待处理",
					"default": 0
				},
				"isDel": {
					"title": "是否删除",
					"bsonType": "int",
					"description": "状态，0 不删，1 删",
					"default": 0
				},
				"createTime": {
					"title": "创建时间",
					"bsonType": "timestamp",
					"defaultValue": {
						"$env": "now"
					}
				}
			},
			"indexes": [{
					"key": {
						"date": 1
					},
					"name": "date_index"
				},
				{
					"key": {
						"vehicle_number": 1
					},
					"name": "vehicle_number_index"
				},
				{
					"key": {
						"customer_name": 1
					},
					"name": "customer_name_index"
				}
			]
		};

		// 创建销售表
		await db.createCollection(salesTableName, salesTableSchema);

		return {
			code: 0,
			message: '注册成功',
			userId
		};
	} catch (error) {
		return {
			code: 1,
			message: '注册失败',
			error
		};
	}
};

// 用户登录
exports.loginUser = async (logData) => {
	const db = uniCloud.database();
	let {
		username,
		password
	} = logData
	try {
		// 查找用户
		const res = await db.collection('users').where({
			username
		}).get();

		if (res.data.length === 0) {
			return {
				code: 1,
				message: '用户名不存在'
			};
		}

		const user = res.data[0];

		// 检查密码是否匹配
		if (user.password !== password) {
			return {
				code: 1,
				message: '密码错误'
			};
		}

		return {
			code: 0,
			message: '登录成功',
			data: user
		};
	} catch (error) {
		return {
			code: 1,
			message: '登录失败',
			error
		};
	}
};



// 更新用户信息
exports.updateUser = async (userId, updateData) => {
	const db = uniCloud.database();

	try {
		const res = await db.collection('users').doc(userId).update(updateData);
		if (res.updated === 0) {
			return {
				code: 1,
				message: '未做任何更改'
			};
		}

		return {
			code: 0,
			message: '更新成功'
		};
	} catch (error) {
		return {
			code: 1,
			message: '更新失败',
			error
		};
	}
};
// 删除用户及其销售表
exports.deleteUser = async (userId, username) => {
	const db = uniCloud.database();

	try {
		// 删除用户
		const res = await db.collection('users').doc(userId).remove();

		if (res.deleted === 0) {
			return {
				code: 1,
				message: '用户删除失败'
			};
		}

		// 删除销售表
		const salesTableName = `${username}-sales`;
		await db.deleteCollection(salesTableName);

		return {
			code: 0,
			message: '删除成功'
		};
	} catch (error) {
		return {
			code: 1,
			message: '删除失败',
			error
		};
	}
};

// 获取用户信息
exports.getUserInfo = async (userId) => {
	const db = uniCloud.database();

	try {
		const res = await db.collection('users').doc(userId).get();
		if (res.data.length === 0) {
			return {
				code: 1,
				message: '用户不存在'
			};
		}

		return {
			code: 0,
			message: '获取成功',
			data: res.data[0]
		};
	} catch (error) {
		return {
			code: 1,
			message: '获取用户信息失败',
			error
		};
	}
};


// 新增用户，不创建销售表
exports.addUser = async (userData) => {
	const db = uniCloud.database();
	const { username, password } = userData;

	// 检查用户名是否已存在
	const existingUser = await db.collection('users').where({
		username
	}).get();
	if (existingUser.data.length > 0) {
		return {
			code: 1,
			message: '用户名已存在'
		};
	}

	try {
		// 插入新用户
		const res = await db.collection('users').add(userData);
		return {
			code: 0,
			message: '新增用户成功',
			userId: res.id
		};
	} catch (error) {
		return {
			code: 1,
			message: '新增用户失败',
			error
		};
	}
};
// 获取用户列表，支持分页和筛选
exports.getUserList = async (query) => {
	const db = uniCloud.database();
	const {
		page = 1,          // 默认第 1 页
		limit = 10,        // 默认每页 10 条
		username = ''      // 可选，按用户名筛选
	} = query;

	try {
		const collection = db.collection('users');
		
		// 构建筛选条件
		let filter = {};
		if (username) {
			filter.username = new RegExp(username, 'i');  // 模糊匹配用户名，忽略大小写
		}

		// 获取总用户数
		const totalRes = await collection.where(filter).count();
		const total = totalRes.total;

		// 分页查询用户
		const res = await collection.where(filter)
			.skip((page - 1) * limit)
			.limit(limit)
			.get();

		return {
			code: 0,
			message: '获取用户列表成功',
			data: {
				total,
				page,
				limit,
				list: res.data
			}
		};
	} catch (error) {
		return {
			code: 1,
			message: '获取用户列表失败',
			error
		};
	}
};



